import { acceptHMRUpdate, defineStore } from "pinia";
import { loginByUsername, logoutAPI } from "../service/user";
import { removeToken, setToken } from "../utils/storage";
import socket from "../utils/socket_io";

export const useUserStore = defineStore({
  id: "user",
  state: () => ({
    token: "",
    userInfo: {},
  }),
  getters: {},
  actions: {
    loginByUsername (userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername({
          username: userInfo.username,
          password: userInfo.password,
          captcha: userInfo.captcha,
        })
          .then((res) => {
            const data = res.data;
            setToken(data.token);
            let socketInfo = {
              user_id: data.user_id,
              realname: data.realname,
              username: data.username,
              phone: data.phone,
              sex: data.sex,
              avatar: data.avatar,
            };
            this.$patch({
              token: data.token,
              userInfo: socketInfo,
            });
            socket.emit("login", socketInfo);
            // emitter.all.clear();
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    FedLogOut () {
      return new Promise((resolve, reject) => {
        logoutAPI()
          .then(() => {
            socket.emit("logout", this.userInfo);
            this.$patch({
              token: "",
              userInfo: {},
            });
            removeToken();
            resolve();
          })
          .catch(() => {
            this.$patch({
              token: "",
              userInfo: {},
            });
            removeToken();
            reject();
          });
      });
    },
  },
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        key: "user",
        storage: localStorage,
      },
    ],
  },
});

// if (import.meta.hot) {
//   import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot));
// }
